package club.framework.web.config;


import club.framework.web.base.common.Constants;
import club.framework.web.base.common.Crypto;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.Properties;

/**
 * @date 2017/9/6.
 * @Email:sunmch@163.com
 * @author: 念梓
 * des:
 */
public class DecryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {


    private static  final Logger log = LogManager.getLogger(DecryptPropertyPlaceholderConfigurer.class);

    /**
     * 解密方式，重写props中的内容
     * @param beanFactoryToProcess
     * @param props
     * @throws BeansException
     */
    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
            throws BeansException {
        try {
            decryptProps(props);
        } catch (Exception e) {
            log.error("解密数据库链接信息失败: ",e);
        }
        super.processProperties(beanFactoryToProcess, props);
    }


    public void decryptProps(Properties properties) throws Exception {

        Crypto crypto = Crypto.getInstance();
        if (properties.get("jdbc.url") != null) {
            String jdbcUrl = properties.get("jdbc.url").toString();
            properties.setProperty("jdbc.url", crypto.decrypt(jdbcUrl, Constants.PROPERTIES_KEY));
        }

        if (properties.get("jdbc.username") != null) {
            String jdbcUsername = properties.get("jdbc.username").toString();
            properties.setProperty("jdbc.username", crypto.decrypt(jdbcUsername, Constants.PROPERTIES_KEY));
        }

        if (properties.get("jdbc.password") != null) {
            String jdbcPassword = properties.get("jdbc.password").toString();
            properties.setProperty("jdbc.password", crypto.decrypt(jdbcPassword, Constants.PROPERTIES_KEY));
        }


    }


}
